"""
路由依赖项
"""
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from typing import Optional

from database import get_db
from tools.auth import verify_token
from view.auth_service import AuthService
from models.models import User

security = HTTPBearer()


async def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
) -> User:
    """
    获取当前登录用户
    
    用于需要认证的接口
    """
    try:
        print(f"[DEBUG] get_current_user called")
        print(f"   Credentials type: {type(credentials)}")
        print(f"   Credentials scheme: {credentials.scheme}")
        token = credentials.credentials
        
        # 调试日志
        print(f"[TOKEN] Received token: {token[:30]}... (length: {len(token)})")
        
        payload = verify_token(token)
        
        if not payload:
            print(f"[ERROR] Token verification failed for token: {token[:30]}...")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的token，请重新登录",
                headers={"WWW-Authenticate": "Bearer"}
            )
        
        user_id_str = payload.get("sub")
        if not user_id_str:
            print(f"[ERROR] Token missing user_id in payload: {payload}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="token中缺少用户ID",
                headers={"WWW-Authenticate": "Bearer"}
            )
        
        # sub 是字符串，需要转换为整数
        try:
            user_id = int(user_id_str)
        except (ValueError, TypeError):
            print(f"[ERROR] Invalid user_id format in token: {user_id_str}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="token中的用户ID格式错误",
                headers={"WWW-Authenticate": "Bearer"}
            )
        
        print(f"[SUCCESS] Token validated for user_id: {user_id}")
        
        user = AuthService.get_user_by_id(db, user_id)
        if not user:
            print(f"[ERROR] User not found: {user_id}")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        if user.status == 0:
            print(f"[ERROR] User account disabled: {user_id}")
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="账号已被禁用"
            )
        
        return user
    except HTTPException:
        raise
    except Exception as e:
        import traceback
        print(f"[ERROR] get_current_user error: {type(e).__name__}: {str(e)}")
        traceback.print_exc()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"用户认证处理失败: {str(e)}"
        )


async def get_current_user_optional(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer(auto_error=False)),
    db: Session = Depends(get_db)
) -> Optional[User]:
    """
    获取当前登录用户（可选）
    
    用于可选认证的接口
    """
    if not credentials:
        return None
    
    token = credentials.credentials
    payload = verify_token(token)
    
    if not payload:
        return None
    
    user_id_str = payload.get("sub")
    if not user_id_str:
        return None
    
    # sub 是字符串，需要转换为整数
    try:
        user_id = int(user_id_str)
    except (ValueError, TypeError):
        return None
    
    user = AuthService.get_user_by_id(db, user_id)
    
    if user and user.status == 0:
        return None
    
    return user

